use crate::MetadataError;
use semver::Version;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;
use std::str::FromStr;

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Pubfile {
    pub releases: Vec<Release>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Release {
    pub version: Version,
    pub revision: String,
}

impl Pubfile {
    pub fn load<T: AsRef<Path>>(path: T) -> Result<Self, MetadataError> {
        let path = path.as_ref().canonicalize()?;
        let text = fs::read_to_string(path)?;
        Self::from_str(&text)
    }

    pub fn save<T: AsRef<Path>>(&self, path: T) -> Result<(), MetadataError> {
        let mut text = String::new();
        text.push_str("# This file is automatically @generated by Veryl.\n");
        text.push_str("# It is not intended for manual editing.\n");
        text.push_str(&toml::to_string(&self)?);
        fs::write(&path, text.as_bytes())?;
        Ok(())
    }
}

impl FromStr for Pubfile {
    type Err = MetadataError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let pubfile: Pubfile = toml::from_str(s)?;
        Ok(pubfile)
    }
}
